﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;

namespace Stockholm.SOA.Kaskelot.WCF.ServiceImplementation.ErrorHandling
{
    class ServiceErrorAttribute : Attribute, IServiceBehavior
    {
        private Type _errorHandler;
        public ServiceErrorAttribute(Type errorHandler)
        {
            _errorHandler = errorHandler;
        }
        void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase) { }
        void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters) { }
        void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
        {
            IErrorHandler errorHandler;
            try
            {
                errorHandler = (IErrorHandler)Activator.CreateInstance(_errorHandler);
            }
            catch (MissingMethodException ex)
            {
                throw new ArgumentException("No parameterless ctor defined on error handler class");
            }
            catch (InvalidCastException ex)
            {
                throw new ArgumentException("Error handler must implement IErrorHandler");
            }

            foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
                channelDispatcher.ErrorHandlers.Add(errorHandler);
            }
        }
    }
 }
